<?php
namespace Home\Controller;

use Think\Controller;

class OnlineOrderController extends BaseController
{
    // 立即支付-创建订单
    public function createOrder()
    {
        $addressId = I("addressId");
        // 地址ID为空
        if (empty($addressId)) {
            $this->ajaxError("未选择地址！");
        }

        $member = parent::get('account');

        //会员
        if (empty($member)) {
            $this->ajaxError("未登录");
        }

        $address = M('memberaddress')->where(array("id" => $addressId))->find();
        // 地址
        if (empty($address) || $address['isDelete'] == 1) {
            $this->ajaxError("地址不存在！");
        }

        //商品id和数量列表
        $products = I('products');
        $products = explode(",", $products);
        //购买商品列表
        if (empty($products)) {
            return $this->ajaxError('购物车为空！');
        }
        $allproductList = M("product")
            ->where(array('isUp' => 1, 'isDelete' => 2))
            ->select();
        //组合列表
        $productList = array();
        foreach ($allproductList as $product) {
            $newProduct = array($product["id"] => array(
                'id' => $product["id"],
                'name' => $product["name"],
                'img' => $product['img'],
                'price' => $product['price'],
                'price1' => $product['price1'],
                'price2' => $product['price2'],
                'price3' => $product['price3'],
                'price4' => $product['price4'],
                'price5' => $product['price5'],
                'price6' => $product['price6'],
                'price7' => $product['price7'],
                'price8' => $product['price8'],
                'price9' => $product['price9'],
                'price10' => $product['price10'],
                'deductible' => $product['deductible'],
                'bonus' => $product['bonus'],
                'bonus2' => $product['bonus2'],
                'introduce' => $product['introduce'],
                'boxnum' => $product['boxnum'],
                'num' => 0
            ));
            foreach ($newProduct as $key => $value) {
                $productList[$key] = $value;
            }
        }

        $cart = array();
        if (!empty($products)) {
            for ($i = 0; $i < count($products); $i = $i + 2) {
                $id = $products[$i];
                $num = ceil($products[$i + 1]);
                if ($num > 0) {
                    //存入数组
                    $cart[$id] = $productList[$id];
                    $cart[$id]['num'] = $num;
                }
            }
        }

        // 购物车为空
        if (empty($cart)) {
            $this->ajaxError("购物车为空！");
        }

        M()->startTrans();
        try {
            //总金额和总消费积分
            //   $total = I("total");
            //  $integral = I("integral");
            $check = I('checked');
            //计算可用积分
            $avlbIntegral = 0;
            //计算付款
            $total = 0;
            foreach ($cart as $product) {
                $avlbIntegral += $product['deductible'] * $product['num'];
                if ($avlbIntegral >= $member['integral']) {
                    $avlbIntegral = $member['integral'];
                    break;
                }
            }
            foreach ($cart as $product) {
                $total += $product['price'] * $product['num'];
            }

            //如果使用积分抵扣
            if ($check == "true") {
                // 积分不足
                if ($member['integral'] <= 0 || $member['integral'] < $avlbIntegral) {
                    $this->ajaxError("积分不足，剩余：" . $member['integral'] . "！");
                }

                $mid = $member['id'];
                // 统计未支付的订单的积分
                $nopayintegral = M("onlineorder")
                    ->where("SourceId = $mid AND orderType = 1 AND `status` = 1")
                    ->sum('integral');

                // 订单积分大于可用积分
                if ($member['integral'] <= $nopayintegral) {
                    $this->ajaxError("订单未支付积分大于可用积分，剩余：" . $member['integral'] . "，订单需支付积分：" . $nopayintegral . "！");
                }
            } else {
                $avlbIntegral = 0;
            }

            //重新计算总价
            $retotal = 0;
            //计算分销奖金
            $bonus = 0;
            $bonus2 = 0;
            //优惠价
            $rebatetotal = 0;
            //代理价
            $totalarray = array();
            foreach ($cart as $product) {
                $retotal += $product['price'] * $product['num'];
                $bonus += $product['price'] * $product['num'] * $product['bonus'] / 100;
                $bonus2 += $product['price'] * $product['num'] * $product['bonus2'] / 100;
                $rebatetotal += $product['rebate'] * $product['num'];
                for ($j = 1; $j <= 10; $j = $j + 1) {
                    $totalarray[$j - 1] += $product['price' . $j] * $product['num'];
                }
            }

            if ($retotal != $total) {
                $this->ajaxError("总价检测错误！");
            }

            //当前商城代理
            $urlagenid = $member['belongagenid'];

//                parent::get('urlagen');
//            //TODO 默认厂家ID
//            $urlagenid = 1;
//            if (!empty($urlagen)) {
//                $urlagenid = $urlagen['id'];
//            }

            // 创建订单
            $order = array(
                'SourceId' => $member['id'],
                'sn' => make_order_sn(),
                'orderType' => '1',
                'payType' => '0',
                'toagenId' => $urlagenid,
                'status' => '1',
                'total' => $retotal,
                'integral' => $avlbIntegral,
                'total1' => $totalarray[0],
                'total2' => $totalarray[1],
                'total3' => $totalarray[2],
                'total4' => $totalarray[3],
                'total5' => $totalarray[4],
                'total6' => $totalarray[5],
                'total7' => $totalarray[6],
                'total8' => $totalarray[7],
                'total9' => $totalarray[8],
                'total10' => $totalarray[9],
                'bonus' => $bonus,
                'bonus2' => $bonus2,
                'isFlow' => '2',
                'createTime' => now_datetime(),
                'updateTime' => now_datetime(),
                'regionId' => $address['regionid'],
                'name' => $address['name'],
                'phone' => $address['phone'],
                'address' => $address['address'],
                'rebatetotal' => $rebatetotal
            );

            $orderId = M('onlineorder')->add($order);

            // 如果出错
            if (!$orderId) {
                M()->rollback();
                $this->ajaxError("创建订单出错！");
            }

            // 插入订单详细
            foreach ($cart as $product) {
                $productId = $product['id'];
                $num = $product['num'];
                $price = $product['price'];
                $total = $num * $price;
                $boxnum = $product['boxnum'];
                $boxs = floor($num / $boxnum);
                if ($boxs >= 1) {
                    $nsstr = floor($num / $boxnum) . '箱' . $num % $boxnum . '盒';
                } else {
                    $nsstr = $num . '盒';
                }

                $orderProduct = array(
                    'orderId' => $orderId,
                    'productId' => $productId,
                    'num' => $num,
                    'price' => $price,
                    'total' => $total,
                    'numShow' => $nsstr
                );

                $productDb = M('product')->where(array("id" => $productId))->find();

                if (empty($productDb) || $productDb['isDelete'] == 1) {
                    M()->rollback();
                    $this->ajaxError('商品ID' . $productId . '错误！');
                }

                $orderProductId = M('orderdetails')->add($orderProduct);

                // 如果出错
                if (!$orderProductId) {
                    M()->rollback();
                    $this->ajaxError("创建订单详细出错！");
                }
            }
            //推送消息-未支付
            $agen = M('agen')->where(array('id' => $member['belongagenid']))->find();
            if ($agen && $agen['pushtag'] != null) {
                send_pub($agen['pushtag'], "尊敬的：" . $agen['account'] . "，会员" . $member['account'] . "给您下单了（尚未支付），请注意哟");
            }
            // 清空购买订单信息
            parent::remove('paycart');
            parent::remove('cart');
            // 提交
            M()->commit();
        } catch (\Exception $e) {
            // 回滚
            M()->rollback();
            $this->ajaxError("处理失败！");
        }

        // 保存订单号等信息
        $data = M('onlineorder')
            ->where("id = $orderId")
            ->find();
        /*array(
        "orderSn" => $order['sn'],
        "address" => $address,
        "orderId" => $orderId,
    );*/
        parent::set("order", $data);

        $this->ajaxSuccess(array('order' => $data));
    }

    /**
     * web端下单格式化购物车提交数据
     */
    public function formatCartData()
    {
        parent::loginCheck();

        //商品id和数量列表
        $products = I('products');
        $products = explode(",", $products);

        $cart = array();
        if (!empty($products)) {
            for ($i = 0; $i < count($products); $i = $i + 2) {
                $id = $products[$i];
                $num = ceil($products[$i + 1]);
                if ($num > 0) {
                    //存入数组
                    $cart[$id]['id'] = $id;
                    $cart[$id]['num'] = $num;
                }
            }
        }

        $addressId = I("addressId");
        $address = M('address')->where(array("id" => $addressId))->find();
        // 地址
        if (empty($address) || $address['isDelete'] == 1) {
            $this->ajaxError("地址不存在！");
        }

        // 购物车为空
        if (empty($cart)) {
            $this->ajaxError("购物车为空！");
        }

        // 清除session购物信息
        parent::remove('paycart');

        // 重置购物车选中商品
        $cart_sess = parent::get('cart');
        foreach ($cart_sess as $k=>$v) {
            foreach($cart as $k1=>$v1) {
                if ($k == $k1) {
                    unset($cart_sess[$k]);
                }
            }
        }
        parent::set('cart', $cart_sess);

        $cart_json = json_encode($cart);
        $this->createOnlineOrder($cart_json, $address);
    }


    /**
     * 下单
     */
    public function createOnlineOrder($cart_json = "", $address = array())
    {
//        $array = array(
//            "3" => array(
//                "id" => 3,
//                "num" => 2,
//            ),
//            "4" => array(
//                "id" => 4,
//                "num" => 3,
//            ),
//        );
//        echo json_encode($array);die;
        parent::loginCheck();

        //防止重复下单
        $last_commit_order = parent::get("LAST_COMMIT_ORDER");
        if ($last_commit_order && time()-$last_commit_order < 10) $this->ajaxError("您的手速太快了，请稍候再试...");
        parent::set("LAST_COMMIT_ORDER", time());

        $member = parent::get('account');

        $cart = stripslashes(htmlspecialchars_decode(trim(I('post.cart'))));  //stripslashed过滤ios带的\

        if (!empty($cart_json)) {
            $cart = $cart_json;   //web端直接参数传值
        }
//        $cart = '{"3":{"id":3,"num":2},"4":{"id":4,"num":3}}'; //测试数据

        if (empty($cart)) $this->ajaxError("参数错误！");
        $cartArr = json_decode($cart, true);
        if (null == $cartArr) $this->ajaxError("参数格式错误！");

        $total = 0;
        $total_num = 0;

        foreach ($cartArr as $k=>$v) {
            if (empty($v['id']) || empty($v['num'] || 0>= $v['num'])) $this->ajaxError("参数格式错误！");
            $productInfo = M('product')->where(array("id"=>$v['id'],"isUp"=>1,"isDelete"=>2))->find();
            if (empty($productInfo)) $this->ajaxError("含有不存在或已删除的商品！");
            if (0 >= $productInfo['price']) $this->ajaxError("商品信息错误！");

            $total += $productInfo['price']*$v['num'];
            $total_num += $v['num'];
        }

        if (0 >= $total_num || 0 >= $total) $this->ajaxError("订单信息错误！");

        //主订单
        $data1 = array(
            "memberId" => $member['id'],
            "no" => make_order_sn(),
            "status" => 1, //已下单状态 ，对应dropdown表
            "total" => $total,
            "num" => $total_num,
            "createTime" => now_datetime(),
            'regionId' => $address['regionid'],
            'name' => $address['name'],
            'phone' => $address['phone'],
            'address' => $address['address'],
        );

        M()->startTrans();
        //写主订单
        $res1 = M('order')->add($data1);
        if (!$res1) {
            M()->rollback();
            $this->ajaxError("订单提交失败:订单主表添加失败！");
        }

        foreach ($cartArr as $k=>$v) {
            $productInfo = M('product')->where(array("id"=>$v['id'],"isUp"=>1,"isDelete"=>2))->find();
            $data2 = array(
                "orderId" => $res1,
                "productId" => $v['id'],
                "num" => $v['num'],
                "price" => $productInfo['price'],
                "total" => $productInfo['price']*$v['num'],
                "createTime" => now_datetime(),
            );
            $res2 = M('orderdetails')->add($data2);
            if (!$res2) {
                M()->rollback();
                $this->ajaxError("订单提交失败:订单详情表添加失败！");
            }
        }

        M()->commit();
        $this->ajaxSuccess(array('order' => $res1));

    }

    // 确认收货
    public function receive()
    {
        // 开始事物
        M()->startTrans();

        $orderId = I('id');
        //$member = parent::getAccount();
        $member = parent::get('account');

        if (empty($member)) {
            $this->ajaxError("未登录");
        }
        $order = M('order')->where(array(
            'id' => $orderId,
            'memberId' => $member['id'],
            'status' => '3'
        ))->find();

        if (empty ($order)) {
            $this->ajaxError("无此订单");
        }

        // 更新订单状态
        $up = M('order')->where(array(
            'id' => $orderId
        ))->setField(array(
            'status' => '4'
        ));

        // 失败
        if (!$up) {
            // 回滚
            M()->rollback();
            $this->ajaxError("更新订单失败");
        }
        M()->commit();
        $this->ajaxSuccess("确认收货成功");
    }

    // 支付成功
    public function paySuccess()
    {
        $this->ajaxSuccess("支付成功");
    }

    /*// 支付-弃用
    public function pay()
    {
        $orderId = I('id');
        if(empty($orderId)){
            $order = parent::get('order');
            $orderId = $order ['id'];
        } else {
            $data = array(
                "id" => $orderId,
            );
            parent::set("order", $data);
        }
        //$orderSn = $order ['orderSn'];
        //$member = parent::getAccount();
        //$memberId = parent::getAccountId();
        $member = parent::get('account');
        $memberId = $member['id'];

        // 订单ID为空
        if (empty($orderId)) {
            $this->ajaxError("订单ID为空");
        }

        $where["id"] = $orderId;
        $where["SourceId"] = $memberId;
        $order = M('onlineorder')->where($where)->find();
        // 订单为空
        if (empty($order)) {
            $this->ajaxError("订单为空");
        }

        if($order['integral'] > $member['integral'] && $order['integral']>0){
            $this->ajaxError("积分不足，无法支付");
        }

        $truepay = $order['total'] - $order['integral'];

        // 付款记录
        $pay = array(
            "sourceId" => $orderId,
            "sourceType" => 1,
            "type" => 1,
            "status" => 2,
            "moneyType" => 2,
            "payment" => "会员订单在线支付",
            "param" => "实付款:".$truepay.",使用积分:".$order['integral'],
            'createTime' => date("Y-m-d H:i:s"),
            "updateTime" => date("Y-m-d H:i:s")
        );
        $payLog = M("pay")->add($pay);

        if (!$payLog) {
            $this->ajaxError("新增付款记录失败");
        }

        // TODO 测试
        parent::notify();

        $this->ajaxSuccess(array('paymentList' => load_payment_config(), 'order' => $order));
    }*/

    // 取消订单
    public function cancel()
    {
        M()->startTrans();
        $orderId = I('id');
        //$member = parent::getAccount();
        //$memberId = parent::getAccountId();
        $memberId = parent::get('account')['id'];
        if (empty($memberId)) {
            $this->ajaxError("未登录");
        }

        if (empty($orderId)) {
            $this->ajaxError("订单ID为空");
        }

        $order = M('order')->where(array("id" => $orderId, "memberId" => $memberId))->find();
        // 订单为空
        if (empty($order)) {
            $this->ajaxError("订单为空");
        }

        // 更新订单状态
        $ok = M('order')->where(array(
            'id' => $orderId,
            'memberId' => $memberId,
            'status' => '1'
        ))->setField(array(
            'status' => '5'
        ));

        if ($ok) {
            M()->commit();
            $this->ajaxSuccess("取消订单成功");
        } else {
            M()->rollback();
            $this->ajaxError("更新订单状态失败");
        }

        /*//更新会员积分-返还积分
        $mok = M('member')->where(array("id" => $memberId))->setField(array(
            "integral" => array('exp', $member ['integral'] + $order['integral'])
        ));

        if ($mok) {
            M()->commit();
            $this->ajaxSuccess("取消订单成功");
        } else {
            M()->rollback();
            $this->ajaxError("更新会员积分失败");
        }*/
    }

    // 我的订单
    public function myOrderList()
    {
        parent::loginCheck();

        $page = (int)I('p') ? (int)I('p') : 0;
        $list = 10;
        $page2 = $page * $list;
        //$memberId = parent::getAccountId();
        $memberId = parent::get('account')['id'];

        $status = (int)I('status');
        if ($status == '' || $status == null || $status == 0) {
            $where = "o.memberId = $memberId ";
        } else {
            $where = "o.memberId = $memberId and o.status = $status";
        }
        $data = M('order')
            ->alias('o')
            ->join('left join t_member m on o.memberId = m.id')
            ->where($where)
            ->field('o.*,m.account memberaccount,m.name membername')
            ->order('createTime desc')
            ->limit($page2, $list)
            ->select();

        foreach ($data as $k => $v) {
            $order_id = $v['id'];

            $firstGoods = M('orderdetails')
                ->alias("d")
                ->field("d.*,p.name,p.img")
                ->join("LEFT JOIN t_product p ON d.productId = p.id")
                ->where(array("orderId"=>$order_id))
                ->find();
            $data[$k]['first_img'] = $firstGoods['img'];
            $data[$k]['first_name'] = $firstGoods['name'];
            $data[$k]['first_price'] = $firstGoods['price'];
        }

        return $this->ajaxSuccess($data);
    }

    //会员订单详情
    public function myonlineorderdetail()
    {
        $orderid = I('orderid');
        $memberId = parent::get('account')['id'];
        if (empty($memberId)) {
            $this->ajaxError("未登录");
        }
        // 订单
        $onlineorder = M('onlineorder')
            ->where("id = $orderid and SourceId = $memberId and orderType = 1")
            ->find();
        if (empty($onlineorder)) {
            $this->ajaxError("此订单不存在！");
        }

        $detail = M('onlineorder')
            ->alias('a')
            ->field('a.id,a.sn,b.productId,c.name,b.total,b.price,b.num,c.boxnum')
            ->join(' left join `orderdetails` b on a.id=b.orderid left join product c on c.id = b.productId')
            ->where("a.id = $orderid")
            ->select();
        if ($detail) {
            return $this->ajaxSuccess(array('detail' => $detail, 'oorder' => $onlineorder));
        } else {
            return $this->ajaxError('没有你要的数据');
        }
    }

    //会员订单详情
    public function orderDetail()
    {
        //订单id
        $id = I('post.id');
        $memberid = parent::get('account')['id'];
        $where = array('o.id' => $id, 'o.memberId' => $memberid);

        $order = M('order')
            ->alias('o')
            ->join('LEFT JOIN t_member m on m.id = o.memberId')
            ->join('LEFT JOIN t_logistics l on l.code = o.logisticsCom')
            ->join('LEFT JOIN t_region r on r.id = o.regionId')
            ->where($where)
            ->field('o.*,o.no sn,m.account fromaccount,m.realName fromname,l.name logstname,r.name_path namepath')
            ->find();

        if (empty($order)) {
            $this->ajaxError("订单不存在");
        }
        $this->ajaxSuccess($order);
    }
}
